// pages/me/orderList/orderList.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    orderInfo: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.cloud.database().collection('orderInfo').where({
      openid: app.globalData.openid
    }).get()
    .then(res=>{
      this.setData({
        orderInfo: res.data,
        active: parseInt(options.active)
      })
      console.log(options.active)
    })
  },
  onChange(event) {
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },
  pay(event){
    let payInfo = null
    let id = event.currentTarget.dataset.id
    //这里rString不确定是否一定要保持和之前一致，先尝试一下
    wx.cloud.database().collection('orderInfo').doc(id).get()
      .then(res => {
        payInfo = res.data
        //console.log(payInfo)
        wx.cloud.callFunction({
          // 云函数名称
          name: 'getPayInfo',
          // 传给云函数的参数
          data: {
            _id: payInfo._id,
            totalFee: payInfo.money,
            openid: payInfo.openid,
            nonceStr: app.globalData.rString
          },
          success: function (res) {
            //console.log(res)
            // 小程序代码
                const payment = res.result.payment
                wx.requestPayment({
                  timeStamp: payment.timeStamp,
                  nonceStr: payment.nonceStr,
                  package: payment.package,
                  signType: 'MD5',
                  paySign: payment.paySign,
                  success(res) {
                    console.log('pay success', res)
                    wx.showToast({
                      title: '支付成功',
                    })
                    wx.cloud.database().collection('orderInfo').doc(payInfo._id).update({
                      data:{
                           status : 0
                      }
                      }).then(res=>{
                          console.log("数据修改成功");
                      }).catch(res=>{
                          console.log("数据修改失败");
                      })
                  },
                  fail(err) {
                    //支付失败后返回
                    wx.showToast({
                      title: '支付失败',
                      icon: 'error'
                    })
                    console.error('pay fail', err)
                  }
                })
          },
          fail: console.error
        })
      })
  },
  onShareAppMessage(res){
    let myObj = {
      title:'琪琪的手工饰品屋',
      path:"/pages/me/orderList/orderList.js",
    }
    return myObj;
  },
  copyText(e){
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function(){
        wx.getClipboardData({
          success: (option) => {
            wx.showToast({
              title: '复制成功',
            })
          },
        })
      }
    })
  }
})